from sqlalchemy import create_engine
from sqlalchemy.orm import  sessionmaker
from kxchina.items import KxchinaItem
from model import Article,Image
import uuid

class sessionMaker(object):
    # initliaze class ,the same to java constructor 
    def __init__(self):
        # get db engine
        mysql_engine = create_engine('mysql+pymysql://root:@localhost:3306/kxdata?charset=utf8',echo=True)
       
        # get session
        Session = sessionmaker(bind=mysql_engine)

        self.opened_session = Session()


    # parse item  to orm model and save to db
    def data_interface(self,item):
        article = Article()
        #article.id = uuid.uuid4
        article.content = item['content'] 
        article.title = item['title']
        article.url = item['url']
        article.extend1 = self.get_uuid()
        self.opened_session.add(article)
        for x in item['images']:
            image = Image()
            image.url = x['url']
            image.path = x['path']
            image.article_id = article.extend1
            self.opened_session.add(image)
        self.opened_session.commit()


    #get a uuid string for relationship
    #the uuid.uuid() function return a function not  string ,so str(...) before return 
    def get_uuid(self):
        return str(uuid.uuid4())




 